Code
library(tidyverse)
library(stringr)Tony Duan
July 11, 2023

mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
make row number into a new column
names mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
str_length()str_replace() and str_replace_all()str_sub()str_to_upper()
str_to_lower()
‘str_to_title()’
https://stringr.tidyverse.org/articles/stringr.html
---
title: "R package:[stringr]"
subtitle: "package for string manipulation"
author: "Tony Duan"
date: "2023-07-11"
categories: [packages]
execute:
warning: false
error: false
format:
html:
toc: true
code-fold: show
code-tools: true
number-sections: true
code-block-bg: true
code-block-border-left: "#31BAE9"
---

# input data
```{r}
library(tidyverse)
library(stringr)
```
```{r}
data001=mtcars
head(data001)
```
make row number into a new column
```{r}
data001 <- cbind(names = rownames(data001), data001)
rownames(data001) <- NULL
head(data001)
```
# length of string with `str_length()`
```{r}
str_length("abc")
```
# replace with `str_replace()` and `str_replace_all()`
```{r}
text001="abcb"
```
```{r}
text001 %>% str_replace('b','1')
```
```{r}
text001 %>% str_replace_all('b','1')
```
# subset string by position with `str_sub()`
```{r}
data001$new_names=data001$names %>% str_sub(2,4)
head(data001 %>% select(new_names,names))
```
# handle case
```{r}
x <- "I like horses."
```
`str_to_upper()`
```{r}
str_to_upper(x)
```
`str_to_lower()`
```{r}
str_to_lower(x)
```
'str_to_title()'
```{r}
str_to_title(x)
```
# make some length
```{r}
data001$new_names=data001$names %>% str_pad(20,"both")
head(data001$new_names)
```
# extracting number from a string
```{r}
library(stringr)
trx='abc1993 ccc'
num=str_extract(trx, "(\\d)+")
num
```
# Reference
https://stringr.tidyverse.org/articles/stringr.html